#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMediaPlayer>
#include <QVideoWidget>
#include <QVBoxLayout>
#include <QPushButton>
#include <QMediaMetaData>

void MainWindow::playVideo()
{
    player->play();
}

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QVBoxLayout* qs = new QVBoxLayout();
    ui->centralwidget->setLayout (qs);


    // 创建播放器和视频窗口
    player = new QMediaPlayer;
    QVideoWidget *videoWidget = new QVideoWidget;
    // videoWidget->setFixedSize (QSize(800,600));
    // 监听媒体加载完成状态
    QObject::connect(player, &QMediaPlayer::mediaStatusChanged, [=](QMediaPlayer::MediaStatus status) {
        if (status == QMediaPlayer::LoadedMedia) {  // 媒体已加载完成
            // 获取视频分辨率元数据
            QSize resolution = player->metaData().value(QMediaMetaData::Resolution).toSize();
            if (!resolution.isEmpty()) {
                qDebug() << "视频宽高：" << resolution;
            } else {
                qDebug() << "未获取到分辨率信息";
            }
            int w = resolution.width ();
            int h = resolution.height ();
            double r = 1.0 * w / h;
            int ww = 800;
            int hh = int(ww / r);
            qDebug() << ww << " " << hh << " s " << w << " " << h;
            // 固定宽高比
            videoWidget->setFixedSize (QSize(ww, hh));
        }
    });
    // 强制拉伸填充窗口（可能变形）
    videoWidget->setAspectRatioMode(Qt::IgnoreAspectRatio);
    // 隐藏黑边（设置背景色透明）
    videoWidget->setStyleSheet("background-color: transparent;");
    player->setVideoOutput(videoWidget);
    videoWidget->show();

    // 加载视频文件（支持 MP4、AVI 等常见格式）
    player->setSource (QUrl::fromLocalFile("/Users/xiaolixi/Desktop/录屏2025-03-01 11.03.06.mov"));


    player->setLoops (-1);
    QPushButton* start = new QPushButton("start");
    qs->addWidget (videoWidget, 0, Qt::AlignHCenter); // 关键：对齐方式
    qs->addWidget (start);
    QObject::connect(start, SIGNAL(pressed()),
                     this,  SLOT(playVideo()));
}

MainWindow::~MainWindow()
{
    delete ui;
}
